from fastapi import HTTPException
from pydantic import BaseModel, Field
from shapely import Point
from ..dependencies import success, router, depens
from ..models.base import Item, Shop

class ShopForm(BaseModel):
    consignee: str = Field(title="收货人", default='', max_length=20)
    mobile: str = Field(title="手机号", default='', max_length=11)
    dist_id: int = Field(title="地区", default=0)
    detail: str = Field(title="详细", default='', max_length=50)

### 列表
@router.get('/shop', tags=['shop'], dependencies=depens(False))
async def index(page: int = 1, size: int = 10):
    select = [Shop.id, Shop.name, Shop.doorhead]
    list = [row for row in Shop.select(*select).order_by(Shop.id).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Shop.select().count()
    })
### 读取
@router.get('/shop/{id}', tags=['shop'], dependencies=depens(False))
async def read(id: int):
    select = [Shop.id, Shop.name, Shop.doorhead]
    model = Shop.select(*select).where(Shop.id==id).get()

    return success({**model.__data__, 'items': [row.__data__ for row in model.items]})

### 创建
@router.post('/shop', tags=['shop'], dependencies=depens())
async def save(post: ShopForm):
    # 使用Shapely生成Point
    location = (10.0, 20.0)
    model = Shop.create({**post, 'location': Point()})
    return success(model.__data__)

### 更新
@router.put('/shop/{id}', tags=['shop'], dependencies=depens())
async def update(id: int, params):
    Shop.update(params).where(Shop.id == id).execute()
    return success()